using System.Collections.Generic;
using System.Linq;
using IQIGame.Onigao.Framework;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class MapLayer : IReusableClass
    {
        public UIMapRoot owner { get; private set; }
        public GameObject root { get; private set; }
        
        public void Bind(UIMapRoot mapRoot, GameObject layerRoot)
        {
            owner = mapRoot;
            root = layerRoot;
        }

        public UIBaseMapSymbol GetSymbol(int entityId)
        {
            return _symbols.GetValueOrDefault(entityId);
        }

        public ICollection<UIBaseMapSymbol> GetAllSymbol()
        {
            return _symbols.Values;
        }
        
        public void AddSymbol(UIBaseMapSymbol symbol)
        {
            RemoveSymbol(symbol.data.entityId);
            ProcessSymbol(symbol);
        }

        public void RemoveSymbol(int entityId)
        {
            if (_symbols.Remove(entityId, out var symbol))
            {
                UIMapManager.Instance.PutSymbol(symbol);
            }
        }

        public void RemoveSymbol()
        {
            if (_symbols.Count > 0)
            {
               var kvp =  _symbols.First();
               _symbols.Remove(kvp.Key);
               UIMapManager.Instance.PutSymbol(kvp.Value);
            }
        }

        private void ProcessSymbol(UIBaseMapSymbol symbol)
        {
            //过滤
            var container = owner.curContainer;
            if (!(container?.FilterMapSymbol(symbol.data) ?? true) || root == null)
            {
                UIMapManager.Instance.PutSymbol(symbol);
                return;
            }

            //设置归属关系
            symbol.owner = owner;
            _symbols[symbol.data.entityId] = symbol;
            //更新显示
            var rt = symbol.transform;
            rt.SetParent(root.transform);
            rt.localScale = Vector3.one;
            rt.localPosition = Vector3.zero;
            symbol.Show();
        }
        
        public void Update(float dt, float unscaledDt)
        {
            foreach (var symbol in _symbols.Values)
            {
                if (!symbol.updatable)
                {
                    continue;
                }

                symbol.Update(dt, unscaledDt);
            }
        }

        public void Clear()
        {
            foreach (var symbol in _symbols.Values)
            {
                UIMapManager.Instance.PutSymbol(symbol);
            }

            _symbols.Clear();
        }

        public uint MaxStore => 10;

        public void OnReset()
        {
            root = null;
            owner = null;
            Clear();
        }

        private readonly Dictionary<int, UIBaseMapSymbol> _symbols = new();
    }
}